package club.zbiao.modules.system.service.query;

import club.zbiao.modules.system.domain.BaseEntity;
import club.zbiao.modules.system.repo.BaseRepository;
import club.zbiao.modules.system.service.BaseQueryService;
import club.zbiao.modules.system.service.dto.BaseDTO;
import club.zbiao.modules.system.service.mapper.BaseMapper;
import club.zbiao.modules.system.service.spec.BaseSpec;
import club.zbiao.utils.PageUtil;
import club.zbiao.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author zbiao
 * @date 2019-05-22
 */
public class BaseQueryServiceImpl<D extends BaseDTO, E extends BaseEntity, M extends BaseMapper<D, E>,S extends BaseSpec<D,E>, R extends BaseRepository<E>> implements BaseQueryService<D, E> {

    @Autowired
    protected R queryRepo;

    @Autowired
    protected M mapper;

    @Autowired
    protected S s;

    @Override
    public D findById(Long id) {
        Optional<E> t = queryRepo.findById(id);
        ValidationUtil.isNull(t, "Dept", "id", id);
        return mapper.toDto(t.get());
    }

    @Override
    public E findOne(Long id) {
        Optional<E> t = queryRepo.findById(id);
        ValidationUtil.isNull(t, "Dept", "id", id);
        return t.get();
    }

    /**
     * 分页
     */

    public Map queryAll(D d, Pageable pageable) {
        s.init(d);
        Page<E> page = queryRepo.findAll(s, pageable);
        return PageUtil.toPage(page.map(mapper::toDto));
    }

    /**
     * 不分页
     */
    public List<D> queryAll(D d) {
        s.init(d);
        List<E> list= queryRepo.findAll(s);
        return mapper.toDto(list);
    }


}